package com.cnebula.uas.authtoken.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cnebula.uas.authtoken.ConfAdmin;
import com.cnebula.uas.authtoken.service.TokenService;
import com.cnebula.uas.authtoken.service.UASService;
import com.cnebula.uas.authtoken.util.Constant;

@RestController
@RequestMapping(value = "/uas/authtoken")
public class AuthTokenController {

	Logger log = LoggerFactory.getLogger(AuthTokenController.class);

	@Autowired
	ConfAdmin conf;

	@Autowired
	TokenService tokenService;

	@Autowired
	UASService uasService;

	@RequestMapping(value = "/token")
	@GetMapping
	public ResponseEntity<String> token(@RequestParam String artifact, HttpServletRequest request, HttpServletResponse response) {

		String okapiURL = request.getHeader(Constant.OKAPI_URL_HEADER);
		String requestToken = request.getHeader(Constant.OKAPI_TOKEN_HEADER);
		String okapiTenant = request.getHeader(Constant.OKAPI_TENANT_HEADER);

		if (requestToken == null) {
			log.error("Missing request token");
			return new ResponseEntity<String>("Missing request token", HttpStatus.BAD_REQUEST);
		}

		ResponseEntity<String> rst = null;
		try {
			rst = uasService.checkArtifact(artifact);
		} catch (Exception e) {
			return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
		}

		String content = rst.getBody();

		Properties prop = new Properties();
		try {
			prop.load(new InputStreamReader(new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)),
					StandardCharsets.UTF_8));
		} catch (IOException e) {
			return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
		}

		String loginStatus = prop.getProperty(Constant.UAS_UM_LOGINSTATUS);
		if (loginStatus == null || !loginStatus.equals("success")) {
			return ResponseEntity.badRequest().body("invalid artifact");
		}

		String localLoginId = prop.getProperty(Constant.UAS_UM_LOCALLOGINID);
		String organizationCode = prop.getProperty(Constant.UAS_UM_ORGANIZATION_CODE);
		
		//TODO 验证租客与artifact是否匹配
		
		
//		String userId = localLoginId + "_" + organizationCode;
		String userId = localLoginId;

		Map<String, String> payload = new HashMap<String, String>();
		payload.put("sub", localLoginId);
		payload.put("user_id", userId);
		String okapiToken = null;
		try {
			rst = tokenService.fetchToken(payload, okapiTenant, okapiURL, requestToken);
			okapiToken = rst.getBody();

		} catch (Exception e) {
			return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
		}
		return ResponseEntity.ok(okapiToken);

	}
}
